package fr.thelem.gestiondemandesthelem.web.commons;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;

/**
 * Outil d'encryption
 */
public class EncryptionTool {

    /** Attribut salt */
    private static byte[] salt = {(byte) 0x03, (byte) 0x09, (byte) 0x02, (byte) 0x08, (byte) 0x01, (byte) 0x02, (byte) 0x04, (byte) 0x03};

    /**
     * Crypte le mot de passe
     * 
     * @param mdp mot de passe à crypter
     * @return mot de passe encrypté
     */
    public static String encrypt(String mdp) {
        String res = "";
        try {
            sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            Cipher encrypter;
            encrypter = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
            encrypter.init(Cipher.ENCRYPT_MODE, getKey(), new javax.crypto.spec.PBEParameterSpec(salt, 20));
            byte[] str = mdp.getBytes("ISO-8859-1");
            byte[] enc = encrypter.doFinal(str);
            res = encoder.encode(enc);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * Decrypte le mot de passe
     * 
     * @param mdp mot de passe encrypté
     * @return mot de passe décrypté
     */
    public static String decrypt(String mdp) {
        String res = "";
        try {
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            Cipher decrypter;
            decrypter = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
            decrypter.init(Cipher.DECRYPT_MODE, getKey(), new javax.crypto.spec.PBEParameterSpec(salt, 20));
            byte[] dec = decoder.decodeBuffer(mdp);
            byte[] str = decrypter.doFinal(dec);
            res = new String(str, "ISO-8859-1");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * Permet de récupérer la clé de cryptage de thélem assurances.
     * 
     * @return clé
     */
    public static SecretKey getKey() {
        SecretKey k = null;
        try {
            SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec("Cl3 d3 crypt@g3 th3l3m @ssur@nc3s".toCharArray()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return k;
    }

    /**
     * test de cryptage
     * 
     * @param args args
     */
    public static void main(String[] args) {
        System.out.println(decrypt("5psLRdCsGuiZAnfGkIQswA=="));

    }
}
